package org.zfes.snowier.cloud.zbss.widget.act.service.impl;

import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.zfes.snowier.core.util.ZObjectUtil;
import com.google.common.collect.Lists;
import org.zfes.snowier.core.exceptions.ServiceLogicalException;
import org.zfes.snowier.core.util.ZAssert;
import org.zfes.snowier.cloud.zbss.widget.act.service.IActQuestionService;
import org.zfes.snowier.cloud.zbss.widget.act.service.IActSubjectQuestionsService;
import org.zfes.snowier.cloud.zbss.widget.act.service.IActSubjectService;
import org.zfes.snowier.cloud.zbss.widget.act.dao.ActSubjectQuestionsMapper;
import org.zfes.snowier.cloud.zbss.widget.act.dto.ActSubjectQuestionsDto;
import org.zfes.snowier.cloud.zbss.widget.act.dto.SubQuestionsDto;
import org.zfes.snowier.cloud.zbss.widget.act.model.ActQuestion;
import org.zfes.snowier.cloud.zbss.widget.act.model.ActSubject;
import org.zfes.snowier.cloud.zbss.widget.act.model.ActSubjectQuestions;
@Service
public class ActSubjectQuestionsServiceImpl implements IActSubjectQuestionsService{
 	@Autowired
	private ActSubjectQuestionsMapper actSubjectQuesMapper;
 	@Autowired
	private IActSubjectService actSubjectService;
 	@Autowired
	private IActQuestionService  actQuestionService;
 	
 	@Transactional(rollbackFor=Exception.class)
 	@Override
	public void createActSubjectQuestions(Long subjectId,List<Long> quesIds,Long creatorUserId) {
 		ZAssert.notNull(subjectId, "请选择课堂");
 		ZAssert.notEmpty(quesIds, "请选择题目");
 		
 		ActSubject actSubject=actSubjectService.loadActSubjectById(subjectId).orElseThrow(()->new ServiceLogicalException("未查询到数据"));
		 
		ZAssert.equals(actSubject.getCreatorUserId(), creatorUserId, "当前课堂不是本人创建");
		//#0未进行， 1进行中，2已结束 -1删除#
		ZAssert.equals(actSubject.getStatus(), Byte.valueOf("0"), "当前课堂不是【未进行】状态");
		
 		List<ActSubjectQuestions> actSubjectQuesList = actSubjectQuesMapper.selectBySubjectId(subjectId,null);
 		
 		//过滤掉已经存在的question
 		if(ZObjectUtil.isNotEmpty(actSubjectQuesList)) {
 			
 			Set<Long> idSet = actSubjectQuesList.stream().map(val->val.getQuesId()).collect(Collectors.toSet());
 			
 			quesIds=quesIds.stream().filter(id->!idSet.contains(id)).collect(Collectors.toList());
 		}
 	
 		for(int i=0;i < quesIds.size(); i++) {
 			actSubjectQuesMapper.insertSelective(
 					new ActSubjectQuestions()
 		 			.setQuesId(quesIds.get(i))
 		 			.setQuesOrder(i+1).setSubjectId(subjectId));
 		}
	}
 	
	@Transactional(rollbackFor=Exception.class)
	@Override
	public void deleteActSubjectQuestions(Long id,Long creatorUserId) {
		ZAssert.notNull(id, "请选择要操作的数据");
		
		ActSubjectQuestions question=loadActSubjectQuestionsById(id).orElseThrow(()->new ServiceLogicalException("未查询到数据"));
		
		ActSubject actSubject=actSubjectService.loadActSubjectById(question.getSubjectId()).orElseThrow(()->new ServiceLogicalException("未查询到数据"));
		
		ZAssert.equals(actSubject.getCreatorUserId(), creatorUserId, "当前课堂不是本人创建");
		//#0未进行， 1进行中，2已结束 -1删除#
		ZAssert.equals(actSubject.getStatus(), Byte.valueOf("0"), "当前课堂不是【未进行】状态");
		
		actSubjectQuesMapper.deleteByPrimaryKey(id);
	}
	
	@Transactional(rollbackFor=Exception.class,readOnly=true)
	@Override
	public Optional<ActSubjectQuestions> loadActSubjectQuestionsById(Long id) {
		if(id!=null){
			return Optional.ofNullable(actSubjectQuesMapper.selectByPrimaryKey(id));
		}
		return Optional.empty();
	}
	
	@Transactional(rollbackFor=Exception.class)
	@Override
	public void updateActSubjectQuesOrder(Long subjectQuesId,Integer newOrder) {
		 if(ZObjectUtil.isNotNull(newOrder)) {
			 actSubjectQuesMapper.updateSubjectQuesOrder(subjectQuesId, newOrder);
		 }
	 }
	
	//============================Process==========================================================
	@Transactional(rollbackFor=Exception.class)
	@Override
	public SubQuestionsDto assignQuestionProcess(List<Long> subjectQuesIds,Long subjectId, Long creatorUserId) {
		ZAssert.notNull(subjectId, "课堂参数错误");
		ZAssert.notEmpty(subjectQuesIds, "请选择题目");

		ActSubject actSubject=actSubjectService.loadActSubjectById(subjectId).orElseThrow(()->new ServiceLogicalException("未查询到数据"));
		ZAssert.equals(actSubject.getCreatorUserId(), creatorUserId, "当前课堂不是本人创建");
		ZAssert.equals(actSubject.getStatus(), Byte.valueOf("1"), "当前课堂不是【进行中】状态");	//#0未进行， 1进行中，2已结束 -1删除#
		
		List<ActSubjectQuestions> actSubjectQuesList = actSubjectQuesMapper.selectByIds(subjectQuesIds);
		
		//过滤掉已经出过的题目，保留未出过的
		actSubjectQuesList = actSubjectQuesList.stream().filter(val->Byte.valueOf("1").equals(val.getStatus())).collect(Collectors.toList());
		
		List<Long> subjectQuesIdsFilterd = actSubjectQuesList.stream().map(val->val.getQuesId()).collect(Collectors.toList());
		
		final List<ActQuestion> questionList = actQuestionService.loadActQuestionsByIds(subjectQuesIdsFilterd);
		
				
		List<ActSubjectQuestionsDto> subQuestionsDtoList=Lists.newArrayList();
		
		actSubjectQuesList.forEach(subQues->{
			//状态_D#1正常，2已出题#
			actSubjectQuesMapper.updateStatus(subQues.getId(), Byte.valueOf("2"));
			
			ActQuestion question=questionList.stream().filter(ques->ques.getId().equals(subQues.getQuesId())).findFirst().orElse(null);
			
			subQuestionsDtoList.add(new ActSubjectQuestionsDto(subQues.getId(), subQues.getQuesOrder(),subQues.getStatus(),  question));
		});
		
	 return new SubQuestionsDto(actSubject,subQuestionsDtoList);
 }
	
	
	
	@Transactional(rollbackFor=Exception.class)
	@Override
	public SubQuestionsDto loadActSubjectQuestionsDto(Long subjectId,Long creatorUserId,Boolean onlyUnAssigned) {
		
		ActSubject actSubject=actSubjectService.loadActSubjectById(subjectId).orElseThrow(()->new ServiceLogicalException("未查询到数据"));
		ZAssert.equals(actSubject.getCreatorUserId(), creatorUserId, "当前课堂不是本人创建");
		ZAssert.equals(actSubject.getStatus(), Byte.valueOf("1"), "当前课堂不是【进行中】状态");//#0未进行， 1进行中，2已结束 -1删除#
		
		Byte statusToQuery=null;
		if(ZObjectUtil.isNotNull(onlyUnAssigned)&&onlyUnAssigned) { //状态_D#1正常，2已出题#
			statusToQuery=Byte.valueOf("1");
		}
		List<ActSubjectQuestions> actSubjectQuesList = actSubjectQuesMapper.selectBySubjectId(subjectId,statusToQuery);
		
		
		final List<ActQuestion>  questionList = actQuestionService.loadActQuestionsByIds(actSubjectQuesList.stream().map(val->val.getQuesId()).collect(Collectors.toList()));
		
		List<ActSubjectQuestionsDto> subQuestionsDtoList=Lists.newArrayList();
		
		actSubjectQuesList.forEach(subQues->{
			
			ActQuestion question= questionList.stream().filter(ques->ques.getId().equals(subQues.getQuesId())).findFirst().orElse(null);
			
			subQuestionsDtoList.add(new ActSubjectQuestionsDto(subQues.getId(), subQues.getQuesOrder(),subQues.getStatus(),  question));
			
		});
		
		return new SubQuestionsDto(actSubject,subQuestionsDtoList);
	}

	
}